package com.demo.myapplication.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.preference.Preference;
import android.support.v7.preference.XpPreferenceFragment;
import android.widget.Toast;

import com.demo.myapplication.R;
import com.demo.myapplication.activity.LoginActivity;

public class SettingsFragment extends XpPreferenceFragment implements Preference.OnPreferenceClickListener {
  private static final String TAG = "SettingsFragment";

  private static final String KEY_MODIFY_PWD = "modify_password";
  private static final String KEY_UPDATE_CONTACT = "update_contact";
  private static final String KEY_ABOUT = "about";
  private static final String KEY_CHECK_UPDATE = "check_update";
  private static final String KEY_FEEDBACK = "feedback";
  private static final String KEY_LOGOUT = "logout";

  @Override
  public void onCreatePreferences2(Bundle savedInstanceState, String rootKey) {
    addPreferencesFromResource(R.xml.setting_preference);
    bindPreferenceClick(KEY_MODIFY_PWD);
    bindPreferenceClick(KEY_UPDATE_CONTACT);
    bindPreferenceClick(KEY_ABOUT);
    bindPreferenceClick(KEY_CHECK_UPDATE);
    bindPreferenceClick(KEY_FEEDBACK);
    bindPreferenceClick(KEY_LOGOUT);
  }

  private void bindPreferenceClick(String key) {
    findPreference(key).setOnPreferenceClickListener(this);
  }


  public static Fragment newInstance(Bundle bundle) {
    SettingsFragment fragment = new SettingsFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override
  public boolean onPreferenceClick(Preference preference) {
    showToast(preference.getKey());
    switch (preference.getKey()) {
      case KEY_LOGOUT:
        showDialog2Exit();
        break;
    }
    return false;
  }

  private AlertDialog dialog;

  private void showDialog2Exit() {
    if (dialog == null) {
      AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
          .setMessage(R.string.ensure_logout)
          .setCancelable(true)
          .setPositiveButton(R.string.logout, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
              logout();
            }
          }).setNegativeButton(R.string.cancel, null);
      dialog = builder.create();
    }
    dialog.show();
  }

  private void logout() {
    //request logout
    startActivity(new Intent(getActivity(), LoginActivity.class));
  }

  private void showToast(String str) {
    Toast.makeText(getContext(), "click " + str, Toast.LENGTH_SHORT).show();
  }
}
